package com.yancloud.android.manager;

import android.os.IBinder;

import com.google.gson.Gson;
import com.koushikdutta.async.http.Multimap;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;
import com.socks.library.KLog;
import com.yancloud.android.reflection.YanCloud;
import com.yancloud.android.reflection.get.GetMessage;
import com.yancloud.android.reflection.get.MainServer;
import com.yancloud.android.reflection.set.Utils;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ias.deepsearch.com.helper.model.dp.AppInfo;
import ias.deepsearch.com.helper.service.DaemonService;
import ias.deepsearch.com.helper.service.FloatWindowService;
import ias.deepsearch.com.helper.util.ShellUtils;
import ias.deepsearch.com.helper.util.normal.FileUtil;

/**
 * Created by root on 7/25/17.
 */

public class IASHandler {

    public final static String TAG = "IASHandler";

    @URLRegx("/uihelper")
    public static void urihelper(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        KLog.v(TAG,"uihelper");
        //TODO 执行获取当前ui的工作
        HashMap<String, Integer> apps = new HashMap<String, Integer>();
        final StringBuilder mark = new StringBuilder();
        IBinder binder = DaemonService.instance.onBind(null);
        try {
            List<PackageVersionPair> appInfos = IAppConnector.Stub.asInterface(binder).listPackages();
            for(int i = 0 ; i < appInfos.size(); i++){
                GetMessage msg  = new GetMessage();
                msg.pkgName = appInfos.get(i).pkgName;
                msg.method = "templateHelper";
                msg.arg = null;
                MainServer.handle(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.send("~~~~~~~success~~~~~~~");
    }
    @URLRegx("/getAppinfo")
    public static void getAppinfo(AsyncHttpServerRequest request, AsyncHttpServerResponse response){
        response.send("success");
    }
    @URLRegx("/inputkeyevent")
    public static void keyEvent(AsyncHttpServerRequest request, AsyncHttpServerResponse response){
        Multimap query = request.getQuery();
        String code = query.getString("code");
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("input keyevent "+code, false);
        response.send("success");
    }
    @URLRegx("/screenshot")
    public static void screenshot(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        ShellUtils.execCommand("screencap -p /sdcard/iasclient.png", true);
        response.sendFile(new File("/sdcard/iasclient.png"));
    }
    @URLRegx("/activity")
    public static void activity(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("dumpsys activity", false);
        String dumpInfo = commandResult.successMsg;
        Pattern p = Pattern.compile("mFocusedActivity:.*\\}");
        Matcher m = p.matcher(dumpInfo);
        String result = "";
        if(m.find()) {
            result = m.group(0);
        }

        int o = result.indexOf("}");
        result = result.substring(0, o + 1);
        response.send(result);
    }
    @URLRegx("/uitree")
    public static void uitree(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send(FileUtil.getContent("/sdcard/ias/ias_gettree"));
    }
    @URLRegx("/intent")
    public static void intent(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send(FileUtil.getContent("/sdcard/ias/ias_getintent"));
    }
    @URLRegx("/screensize")
    public static void screensize(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("wm size", false);
        response.send(commandResult.successMsg);
    }
    @URLRegx("/test")
    public static void test(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        Multimap query = request.getQuery();
        String package_name = query.getString("package");
        String type = query.getString("type");
        String params = query.getString("params");
        KLog.v("deeplink",package_name);
        KLog.v("deeplink",type);
        KLog.v("deeplink",params);
        startDeepLink(package_name, type, params);
        response.send(package_name + " " + type + " " + params);
    }
    @URLRegx("/getcontent")
    public static void getContent(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        Multimap query = request.getQuery();
        int type = Integer.parseInt(query.getString("type"));
        String pkgName = getActiveApp();
        if(pkgName == null){
            response.send("不支持当前App，缺少知识图谱");
            return;
        }
        String content = getActiveContent(pkgName, type);
        DaemonService.notifyFloatWindow(content);
        response.send(content);
        KLog.v(TAG, "getcontent done");
    }

    @URLRegx("/test111")
    public static void test111(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        Multimap query = request.getQuery();
        String content = query.getString("message");
        boolean isShow = Boolean.valueOf( query.getString("isShow"));
        FloatWindowService.updateFloatWindow(content,isShow);
        response.send(content);
    }

    private static void startDeepLink(String package_name, String type, String params){
        try{
            com.yancloud.android.reflection.set.ACache aCache = Utils.getACache();
            aCache.put("preClass", "");
            YanCloud.fromSet(DaemonService.instance.getApplicationContext()).set(package_name, type, params);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String getActiveApp(){
        try {
            GetMessage listMsg = new GetMessage();
            listMsg.pkgName = "";
            listMsg.method = "listPackages";
            listMsg.arg = "";
            String ret = MainServer.handle(listMsg);
            KLog.v("DaemonService","listPackages:\n"+ret);
            Map<String,String> map = new Gson().fromJson(ret, Map.class);
            for (String key:map.keySet()){
                GetMessage msg = new GetMessage();
                msg.pkgName = key;
                msg.method = "isForeground";
                msg.arg = "";
                String str = MainServer.handle(msg);
                KLog.v("DaemonService",key+" isForeground:"+str);
                if (str.equals("yes"))
                    return key;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getActiveContent(String pkgName, int type){
        GetMessage msg = new GetMessage();
        msg.pkgName = pkgName;
        msg.method = "currentContent";
        msg.arg = null;
        GetMessage liveUIMsg = new GetMessage();
        liveUIMsg.pkgName = pkgName;
        liveUIMsg.method = "liveUI";
        liveUIMsg.arg = "true";
        String content;
        if(type == 0)
            content = MainServer.handle(msg);
        else
            content = MainServer.handle(liveUIMsg);
        return content;
    }
}
